<template>
  <div class="auth-container">
    <div class="auth-box">
      <!-- 关闭按钮 -->
      <div class="close-btn" @click="$emit('close')">
        <el-icon><Close /></el-icon>
      </div>

      <div class="auth-header">
        <div class="header-icon">
          <img :src="isLogin ? loginIcon : registerIcon" :alt="isLogin ? '登录' : '注册'" class="mode-icon">
        </div>
        <h2>{{ isLogin ? '登录' : '注册' }}</h2>
        <p class="subtitle">{{ isLogin ? '欢迎回来！' : '创建新账号' }}</p>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-position="top"
        class="auth-form"
      >
        <!-- 头像上传（仅注册时显示） -->
        <el-form-item v-if="!isLogin" label="头像" prop="avatar" class="avatar-form-item">
          <div class="avatar-upload">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.avatar" :src="form.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <p class="upload-tip">点击上传头像</p>
          </div>
        </el-form-item>

        <div class="form-content">
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 邮箱（仅注册时显示） -->
          <el-form-item v-if="!isLogin" label="邮箱" prop="email">
            <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 确认密码（仅注册时显示） -->
          <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item label="验证码" prop="captcha">
            <div class="captcha-container">
              <el-input
                v-model="form.captcha"
                placeholder="请输入验证码"
              >
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
              <img
                :src="captchaUrl"
                alt="验证码"
                class="captcha-img"
                @click="refreshCaptcha"
              />
            </div>
          </el-form-item>

          <!-- 记住我（仅登录时显示） -->
          <el-form-item v-if="isLogin" class="remember-me">
            <el-checkbox v-model="form.remember">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </el-form-item>

          <!-- 提交按钮 -->
          <el-form-item class="submit-form-item">
            <el-button
              type="primary"
              :loading="loading"
              class="submit-btn"
              @click="handleSubmit"
            >
              <img :src="isLogin ? loginIcon : registerIcon" :alt="isLogin ? '登录' : '注册'" class="btn-icon">
              {{ isLogin ? '登录' : '注册' }}
            </el-button>
          </el-form-item>

          <!-- 切换登录/注册 -->
          <div class="auth-switch">
            <span>{{ isLogin ? '还没有账号？' : '已有账号？' }}</span>
            <el-link type="primary" @click="toggleMode">
              {{ isLogin ? '立即注册' : '立即登录' }}
            </el-link>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Key, Plus, Close } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import loginIcon from '@/assets/icons/login.svg'
import registerIcon from '@/assets/icons/register.svg'

export default defineComponent({
  name: 'AuthView',
  components: {
    User,
    Lock,
    Message,
    Key,
    Plus,
    Close
  },
  props: {
    type: {
      type: String,
      default: 'login'
    }
  },
  setup(props, { emit }) {
    const formRef = ref<FormInstance>()
    const loading = ref(false)
    const captchaUrl = ref('/api/captcha')

    const form = ref({
      username: '',
      password: '',
      confirmPassword: '',
      email: '',
      avatar: '',
      captcha: '',
      remember: false
    })

    const isLogin = computed(() => props.type === 'login')

    const validatePass = (rule: any, value: string, callback: any) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (form.value.confirmPassword !== '') {
          formRef.value?.validateField('confirmPassword')
        }
        callback()
      }
    }

    const validatePass2 = (rule: any, value: string, callback: any) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== form.value.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const rules = computed<FormRules>(() => ({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, validator: validatePass, trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, validator: validatePass2, trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 4, message: '验证码长度应为4位', trigger: 'blur' }
      ]
    }))

    const handleAvatarSuccess = (response: any) => {
      form.value.avatar = response.url
    }

    const beforeAvatarUpload = (file: File) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }

    const refreshCaptcha = () => {
      captchaUrl.value = `/api/captcha?t=${Date.now()}`
    }

    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        loading.value = true

        // 这里添加实际的登录/注册逻辑
        const response = await fetch(`/api/${isLogin.value ? 'login' : 'register'}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(form.value)
        })

        if (response.ok) {
          ElMessage.success(isLogin.value ? '登录成功' : '注册成功')
          emit('close')
        } else {
          throw new Error('操作失败')
        }
      } catch (error) {
        ElMessage.error(error instanceof Error ? error.message : '操作失败')
      } finally {
        loading.value = false
      }
    }

    const toggleMode = () => {
      emit('update:type', isLogin.value ? 'register' : 'login')
      formRef.value?.resetFields()
    }

    return {
      formRef,
      form,
      rules,
      loading,
      isLogin,
      captchaUrl,
      handleAvatarSuccess,
      beforeAvatarUpload,
      refreshCaptcha,
      handleSubmit,
      toggleMode,
      loginIcon,
      registerIcon
    }
  }
})
</script>

<style scoped>
.auth-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.75);
  backdrop-filter: blur(10px);
  padding: 2rem;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
}

.auth-box {
  width: 100%;
  max-width: 580px;
  background: #ffffff;
  border-radius: 32px;
  padding: 3.5rem 3rem;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  position: relative;
  transform: translateY(0);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(255, 255, 255, 0.1);
  overflow: hidden;
}

.auth-box::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #66b1ff, #409EFF);
  background-size: 200% 100%;
  animation: gradient 3s linear infinite;
}

@keyframes gradient {
  0% { background-position: 0% 50%; }
  100% { background-position: 200% 50%; }
}

.auth-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 25px 70px rgba(0, 0, 0, 0.2);
}

.close-btn {
  position: absolute;
  top: 1.5rem;
  right: 1.5rem;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.03);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #666;
  z-index: 1;
}

.close-btn:hover {
  background: rgba(0, 0, 0, 0.08);
  color: #333;
  transform: rotate(90deg);
}

.auth-header {
  text-align: center;
  margin-bottom: 3rem;
  position: relative;
}

.auth-header h2 {
  font-size: 2.4rem;
  color: #333;
  margin-bottom: 1rem;
  font-weight: 700;
  background: linear-gradient(45deg, #1a1a1a, #4a4a4a);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: -0.5px;
}

.subtitle {
  color: #666;
  font-size: 1.2rem;
  font-weight: 500;
  opacity: 0.9;
}

.auth-form {
  margin-top: 2rem;
  display: flex;
  gap: 2rem;
}

.avatar-form-item {
  flex: 0 0 auto;
  margin-bottom: 0;
}

.form-content {
  flex: 1;
  min-width: 0;
}

.avatar-upload {
  text-align: center;
  margin-bottom: 0;
}

.avatar-uploader {
  border: 2px dashed #e0e0e0;
  border-radius: 16px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
  margin: 0 auto;
  transition: all 0.3s ease;
  background: rgba(64, 158, 255, 0.02);
}

.avatar-uploader:hover {
  border-color: #409EFF;
  background: rgba(64, 158, 255, 0.05);
  transform: scale(1.02);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
  transition: all 0.3s ease;
}

.avatar-uploader:hover .avatar-uploader-icon {
  color: #409EFF;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
  border-radius: 16px;
}

.upload-tip {
  margin-top: 0.8rem;
  color: #666;
  font-size: 0.9rem;
  font-weight: 500;
}

.captcha-container {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.captcha-img {
  height: 44px;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.captcha-img:hover {
  opacity: 0.8;
  transform: scale(1.02);
}

.remember-me {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.header-icon {
  margin-bottom: 1.5rem;
  display: flex;
  justify-content: center;
}

.mode-icon {
  width: 48px;
  height: 48px;
  color: #409EFF;
  filter: drop-shadow(0 2px 4px rgba(64, 158, 255, 0.2));
}

.submit-form-item {
  margin-bottom: 0;
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}

.submit-btn {
  width: 100%;
  max-width: 300px;
  height: 52px;
  font-size: 1.1rem;
  font-weight: 600;
  background: linear-gradient(45deg, #409EFF, #66b1ff);
  border: none;
  transition: all 0.3s ease;
  letter-spacing: 0.5px;
  text-transform: uppercase;
  font-size: 0.95rem;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.btn-icon {
  width: 20px;
  height: 20px;
  filter: brightness(0) invert(1);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
}

.submit-btn:active {
  transform: translateY(0);
}

.auth-switch {
  text-align: center;
  margin-top: 2.5rem;
  color: #666;
  font-size: 1.1rem;
  font-weight: 500;
}

.auth-switch .el-link {
  margin-left: 0.5rem;
  font-weight: 600;
  font-size: 1.1rem;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #333;
  font-size: 1.1rem;
  margin-bottom: 0.5rem;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #e0e0e0 inset;
  transition: all 0.3s ease;
  padding: 0 15px;
  height: 48px;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409EFF inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF inset;
}

:deep(.el-input__wrapper.is-focus .el-input__prefix) {
  color: #409EFF;
}

:deep(.el-input__inner) {
  height: 48px;
  font-size: 1rem;
}

:deep(.el-input__prefix) {
  color: #909399;
  font-size: 18px;
  margin-right: 8px;
}

@media (max-width: 768px) {
  .auth-form {
    flex-direction: column;
    gap: 1.5rem;
  }

  .avatar-form-item {
    margin-bottom: 1.5rem;
  }

  .avatar-uploader,
  .avatar-uploader-icon,
  .avatar {
    width: 100px;
    height: 100px;
  }

  .avatar-uploader-icon {
    line-height: 100px;
    font-size: 24px;
  }
}
</style> 